import React, {Component} from 'react';
import {Button, Input, Select, Form, Radio, Upload, Icon, Modal, Table, Checkbox, message, InputNumber} from 'antd';
import {connect} from 'react-redux';
import lrz from 'lrz';
import action from '../../store/actions/generatingGoods';
import BraftEditor from './BraftEditor';
import {addGoodsData, updateGoodData} from '../../api';
import './GeneratingGoods.scss';

const {Option} = Select;
const {TextArea} = Input;

function validatePrimeNumber(number) {
  if (number >= 1) {
    return {
      validateStatus: 'success',
      errorMsg: null
    };
  }
  return {
    validateStatus: 'error',
    errorMsg: '请输入大于0的库存!'
  };
}

class GeneratingGoods extends Component {
  state = {
    number: {
      value: 10000
    },
    defaultSupplierId: 0,
    supplierId: 0,
    spec_content: {},   // 规格内容  包括编辑状态下的默认值 以及非编辑状态下的默认值
    isEdit: null,
    formLayout: 'horizontal',
    // 上传开始
    previewVisible: false,
    previewImage: '',
    fileList: [
      {
        uid: '-1',
        name: 'xxx.png',
        status: 'done',
        url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
      }
    ],
    // 上传结束
    columns1: [
      {
        title: '可选规格',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '规格内容',
        key: 'tags',
        dataIndex: 'tags',
        render: (text, dataIndex) => {
          console.log(dataIndex);
          dataIndex.children && dataIndex.children.map(item => (
            <Radio.Group onChange={this.specsContentChange} value={this.state.spec_content} key={item.id}>
              <Radio value={item.id} key={item.id}>{item.name}</Radio>
            </Radio.Group>
          ));
        }
      }
    ]
  };

  handleOk = async (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (this.state.isEdit) {
          // 修改商品接口
          // 商品图片处理开始
          const temp = [...this.state.fileList];
          if (temp[0].uid === '-1') {
            temp.shift();
          }
          let myTemp = [];

          // 真实图片开始
          const image = temp.map(item => {
            console.log(item);
            return item.url || item.originimage;
          });
          // 真实图片结束

          // 缩略图开始
          // const image = temp.map(item => {
          //   console.log(item);
          //   return item.url || item.thumbUrl;
          // });
          // 缩略图结束

          // 增加的invcode cate_code 物料编码 路由传值
          let routeProps = JSON.parse(this.props.match.params.codes);

          const {id, invcode, cate_code} = routeProps;
          const {attcmp, is_virtual, vendor_code, postal_template_id, qty, min_order, is_postal, selling, desc, weight, name, specStatus, market, theDateOfIssuance} = values;

          const param = {
            cate_code,
            invcode,
            image,
            attcmp,
            is_virtual,
            vendor_code,
            postal_template_id,
            qty,
            min_order,
            is_postal,
            selling,
            desc,
            weight,
            name,
            market,
            theDateOfIssuance,
            spec_status: specStatus,
            norm: this.state.spec_content,
            parameter: this.props.braftEditorContent
          };


          // console.log(param);
          // return false;

          updateGoodData(param, id)
            .then(res => {
              console.log(res);
              setTimeout(() => {
                window.close();
              }, 2000);

            })
            .catch(err => {
              console.log(err);
            });

        } else {
          // 生成商品的

          // 商品图片处理开始
          // 真实图片开始
          const temp = [...this.state.fileList];
          if (temp[0].uid === '-1') {
            temp.shift();
          }
          const image = temp.map(item => {
            return item.originimage;
          });
          // 真实图片结束


          // 缩略图开始
          // const temp = [...this.state.fileList];
          // if (temp[0].uid === "-1") {
          //   temp.shift();
          // }
          // const image = temp.map(item => {
          //   return item.thumbUrl;
          // });
          // 缩略图结束

          // // 商品图片处理结束

          // 商品规格的具体内容 this.state.spec_content)
          // 增加的invcode cate_code 物料编码 路由传值
          let routeProps = JSON.parse(this.props.match.params.codes);
          const {invcode, cate_code} = routeProps;
          const {attcmp, is_virtual, vendor_code, postal_template_id, qty, min_order, is_postal, selling, desc, weight, name, specStatus, market, theDateOfIssuance} = values;
          const param = {
            cate_code,
            invcode,
            image,
            attcmp,
            is_virtual,
            vendor_code,
            postal_template_id,
            qty,
            min_order,
            is_postal,
            selling,
            desc,
            weight,
            name,
            market,
            theDateOfIssuance,
            spec_status: specStatus,
            norm: this.state.spec_content,
            parameter: this.props.braftEditorContent
          };

          // console.log(param);
          // return false;

          // 规格组的内容parameter: this.props.braftEditorContent, // 富文本内容spec_status: specStatus,invcode,cate_code
          addGoodsData(param)
            .then(res => {
              console.log(res);
              // setTimeout(() => {
              //   window.close();
              // }, 2000);
            })
            .catch(err => {
              console.log(err);
            });
        }
      }
    });
  };

  clearFrom = () => {
    this.props.form.resetFields();
  };
  // 数字控制
  handleNumberChange = value => {
    this.setState({
      number: {
        ...validatePrimeNumber(value),
        value
      }
    });
  };

  // 上传开始
  handleCancel = () => this.setState({previewVisible: false});

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
    }
    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true
    });
  };

  getBase64 = file => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  };

  // 缩略图图片
  // handlePicChange = ({fileList}) => {
  //   this.setState({fileList});
  // };

  // 真实图片
  handlePicChange = async (file) => {
    let fileList = file.fileList;
    console.log(file, file.file['uid']);
    if (file.file.uid.endsWith('wangbadan')) {  // wangbadan   是自己加的为了分辨出图片来源
      // 说明是编辑复原后的图片
      this.setState({fileList});
    } else {
      // 生成商品的图片
      let tempImage = await this.getBase64(file.file.originFileObj);
      //不压缩
      // const tempfileList = fileList.map(item => {
      //   if (item.originimage) {
      //     return item;
      //   } else {
      //     return {
      //       ...item,
      //       originimage: tempImage
      //     };
      //   }
      // });
      // this.setState({fileList: tempfileList});

      // 压缩 大图片压缩好用 小图片基本上不被压缩
      lrz(tempImage)
        .then(rst => {
          // 处理成功会执行
          const tempfileList = fileList.map(item => {
            if (item.originimage) {
              return item;
            } else {
              return {
                ...item,
                originimage: rst.base64
              };
            }
          });
          this.setState({fileList: tempfileList});
        })
        .catch(err => {
          // 处理失败会执行
          console.log(err);
        })
        .always(() => {
          // 不管是成功失败，都会执行
        });

    }
  };


  // 上传结束

  // 规格内容

  specsContentChange = (e, id) => {
    this.setState(prevState => {
      return {
        spec_content: {...prevState.spec_content, [id]: e.target.value}
      };
    });
  };

  // 供应商改变
  handleSupplierChange = supplier => {
    console.log(supplier);
    this.setState({
      supplierId: supplier
    });
    //  实体 虚拟的辨别处理
    this.props.GET_LOGISTICS_TEMPLATE(supplier);
  };


  initPages = async () => {
    this.clearFrom();
    const {
      GET_SPEC_CHANGE_DATA,
      GET_SOPPLIER_DATA,
      GET_LOGISTICS_TEMPLATE,
      EDIT_GOOD_DATA,
      match
    } = this.props;

    await GET_SOPPLIER_DATA();
    // 选出供应商为实体的 code
    this.props.sopplierData.forEach(item => {
      if (item.username === '长春文德孚智能科技有限公司') {
        this.setState({
          defaultSupplierId: item.id
        });
      }
      return;
    });
    let routeProps = JSON.parse(match.params.codes);
    await GET_SPEC_CHANGE_DATA(routeProps.cate_code);

    this.clearFrom();

    const isEdit = routeProps.hasOwnProperty('id');
    this.setState(prevState => {
      return {
        isEdit
      };
    });

    if (isEdit) {
      await EDIT_GOOD_DATA(routeProps.id).then(res => {
        const {image, logo, norm, vendor_code} = res.data;
        GET_LOGISTICS_TEMPLATE(vendor_code);  // 获取供应商模板

        // 规格复原
        if (norm) {  // 如果有规格 则重新渲染  否则 不改变
          this.setState(prevState => {
            return {
              spec_content: Object.assign({}, JSON.parse(norm))
            };
          });
        }

        // 图片复原
        var mylogo = {};
        let myTemp = [];
        if (logo) {  // 如果有logo 进行logo处理
          mylogo = {
            uid: `-${Math.floor(Math.random() * 10000000000)}wangbadan`,
            name: `${Math.floor(Math.random() * 10000000000)}.png`,
            status: 'done',
            url: logo
          };

          if (image) {   // 如果有图片的话做图片处理
            myTemp = image.map(item => {
              return {
                uid: `-${Math.floor(Math.random() * 10000000000)}wangbadan`,
                name: `${Math.floor(Math.random() * 10000000000)}.png`,
                status: 'done',
                url: item
              };
            });
            myTemp = [...this.state.fileList, mylogo, ...myTemp];
          } else {
            myTemp = [...this.state.fileList, mylogo];
          }
          // 重新渲染图片
          this.setState(prevState => {
            return {
              fileList: myTemp
            };
          });
        }
      });
    } else {
      // 非编辑状态下  状态默认值得处理
      if (this.props.specChangeData) {
        this.defaultState();
      } else {
        message.error('请返回规格库 维护规格中的状态...');
      }
    }

  };

  // 非编辑状态下 获取数据商品规格中状态的值 赋值给状态的第一个
  defaultState = () => {
    let defaultMySpec = {};
    this.props.specChangeData.forEach(item => {
      if (item.name === '状态') {
        let value = item.children[0].id;
        defaultMySpec = {[item.id]: value};
      }
    });
    this.setState(prevState => {
      return {
        spec_content: Object.assign({}, JSON.parse(JSON.stringify(defaultMySpec)))
      };
    });
  };

  componentDidMount() {
    this.initPages();
  }

  render() {
    const {number} = this.state; // 控制数字
    const tips = '请输入大于0的整数...';
    const tips2 = '请输入大于0.01的价格...';
    // 供应商数据   props的 store数据
    const {
      sopplierData,
      specChangeData,
      logisticsTemplate,
      editGoodData
    } = this.props;
    const {getFieldDecorator} = this.props.form;
    // 布局开始
    const {formLayout, spec_content, previewVisible, previewImage, fileList, isEdit} = this.state;
    const formItemLayout =
      formLayout === 'horizontal' ? {labelCol: {span: 3}, wrapperCol: {span: 21}} : null;
    const buttonItemLayout =
      formLayout === 'horizontal' ? {wrapperCol: {span: 14, offset: 4}} : null;
    // 布局结束

    // 上传开始
    const uploadButton = (<div><Icon type="plus"/>
      <div className="ant-upload-text">Upload</div>
    </div>);
    // 上传结束
    return (
      <div className='GeneratingGoods'>
        <h1>商 品</h1>
        <Form className="drawer-form" onSubmit={this.handleOk} layout={formLayout}>

          <Form.Item label="所属公司"{...formItemLayout}>
            {getFieldDecorator('attcmp', {
              initialValue: isEdit ? editGoodData.attcmp + '' : '',
              rules: [{required: true, message: '请选择计量单位组类型...'}]
            })(
              <Radio.Group disabled={isEdit}>
                <Radio value="1">吉林文德孚</Radio>
                <Radio value="2">长春文德孚</Radio>
                <Radio value="3">文德孚上海</Radio>
                <Radio value="4">文德孚里奥</Radio>
              </Radio.Group>
            )}
          </Form.Item>

          <Form.Item label="实体/虚拟"{...formItemLayout}>
            {getFieldDecorator('is_virtual', {
              initialValue: isEdit ? editGoodData.is_virtual + '' : this.state.supplierId === this.state.defaultSupplierId ? '1' : '0',
              rules: [{required: true, message: '请选择实体/虚拟...'}]
            })(
              // <Radio.Group disabled={isEdit}>
              //   <Radio value="1">实体</Radio>
              //   <Radio value="0">虚拟</Radio>
              // </Radio.Group>
              <Radio.Group disabled>
                <Radio value="1">实体</Radio>
                <Radio value="0">虚拟</Radio>
              </Radio.Group>
            )}
          </Form.Item>

          <Form.Item label="商品名称" {...formItemLayout}>
            {getFieldDecorator('name', {
              initialValue: isEdit ? editGoodData.name : '',
              rules: [{required: true, message: '请填写名称...'}]
            })(
              <Input placeholder='计量单位组类型' className='clearValue'/>
            )}
          </Form.Item>

          {/*库存量*/}
          <Form.Item label="库存量" {...formItemLayout} help={number.errorMsg || tips}>
            {getFieldDecorator('qty', {
              initialValue: isEdit ? editGoodData.qty : '',
              rules: [{required: true, message: '请填写库存量...'}]
            })(
              <InputNumber min={1} value={number.value} onChange={this.handleNumberChange} disabled/>

              // <Input placeholder='库存量' className='clearValue'/>
            )}
          </Form.Item>

          <Form.Item label="最小订货量" {...formItemLayout} help={number.errorMsg || tips}>
            {getFieldDecorator('min_order', {
              initialValue: isEdit ? editGoodData.min_order : '',
              rules: [{required: true, message: '请填写最小订货量...'}]
            })(
              <InputNumber min={1} value={number.value} onChange={this.handleNumberChange}/>
              // <Input placeholder='最小订货量' className='clearValue'/>
            )}
          </Form.Item>

          <Form.Item label="商品重量" {...formItemLayout}>
            {getFieldDecorator('weight', {

              initialValue: isEdit ? editGoodData.weight : '',
              rules: [{required: true, message: '请填写商品重量...'}]
            })(
              <Input placeholder='商品重量' className='clearValue'/>
            )}
          </Form.Item>

          <Form.Item label="是否包邮"{...formItemLayout}>
            {getFieldDecorator('is_postal', {
              initialValue: isEdit ? editGoodData.is_postal + '' : '',
              rules: [{required: true, message: '请选择是否包邮...'}]
            })(
              <Radio.Group>
                <Radio value="0">不包邮</Radio>
                <Radio value="1">包邮</Radio>
              </Radio.Group>
            )}
          </Form.Item>

          <Form.Item label="供应商" {...formItemLayout}>
            {getFieldDecorator('vendor_code', {
              initialValue: isEdit ? editGoodData.vendor_code + '' : '',  // 接口属性为：number 形式
              rules: [{required: true, message: '请选择供应商...'}]
            })(
              <Select
                disabled={isEdit}
                placeholder="供应商"
                onChange={this.handleSupplierChange}
              >
                {
                  sopplierData && sopplierData.map(item => (
                    <Option value={item.id} key={item.id}>{item.username}</Option>
                  ))
                }
              </Select>
            )}
          </Form.Item>

          <Form.Item label="快递模板" {...formItemLayout}>
            {getFieldDecorator('postal_template_id', {
              initialValue: isEdit ? +editGoodData.postal_template_id : '',
              rules: [{required: true, message: '请选择快递模板...'}]
            })(
              <Select
                placeholder="快递模板"
              >
                {
                  logisticsTemplate && logisticsTemplate.map(item =>
                    <Option value={item.id}>{item.template_name}</Option>
                  )
                }
              </Select>
            )}
          </Form.Item>

          <Form.Item label="商品图片" {...formItemLayout}>
            {getFieldDecorator('good_pictures', {
              // initialValue: is_virtual ? '实体' : '虚拟',
              // rules: [{required: true, message: '请上传商品图片...'}],
            })(
              <div className="clearfix">
                <Upload
                  action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                  listType="picture-card"
                  fileList={fileList}
                  onPreview={this.handlePreview}
                  onChange={this.handlePicChange}
                >
                  {fileList.length >= 6 ? null : uploadButton}
                </Upload>
                <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                  <img alt="example" style={{width: '100%'}} src={previewImage}/>
                </Modal>
              </div>
            )}
          </Form.Item>
          {/*该处理的问题的地方*/}
          <p style={{
            textIndent: 113,
            color: 'red',
            marginBottom: 10
          }}>{editGoodData.norm_name && editGoodData.norm_name}</p>
          <Form.Item label="商品规格" {...formItemLayout}>
            {getFieldDecorator('specifications', {
              initialValue: isEdit ? spec_content.toString() : '',
              rules: [{
                // required: true,
                // message: '请续选择库存状态...'
              }]
            })(
              <>
                <ul id='specChangeData' style={{borderBottom: '1px solid #ccc', borderRight: '1px solid #ccc'}}>
                  {
                    specChangeData && specChangeData.map((item, index) => (
                      <li key={item.id} className='specChangeData__item' style={{
                        display: 'flex',
                        flexDirection: 'row',
                        backgroundolor: 'red',
                        borderTop: '1px solid #ccc',
                        borderLeft: '1px solid #ccc'
                      }}>
                        <div style={{width: '120px', borderRight: '1px solid #ccc', padding: '5px'}}>{item.name}</div>
                        <Radio.Group
                          style={{flex: '1', padding: '5px'}}
                          onChange={(e) => this.specsContentChange(e, item.id)}
                          value={this.state.spec_content[item.id]}
                          key={item.id}

                        >
                          {
                            item.children && item.children.map(val => (
                              <Radio value={val.id} key={val.id}>{val.name}</Radio>
                            ))
                          }
                        </Radio.Group>
                      </li>
                    ))

                  }
                </ul>
              </>
            )}
          </Form.Item>

          <Form.Item label="市场价格" {...formItemLayout} help={number.errorMsg || tips2}>
            {getFieldDecorator('market', {
              initialValue: isEdit ? editGoodData.market : '',
              rules: [{required: true, message: '请填写市场价格...'}]
            })(
              <InputNumber min={0.01} value={number.value} onChange={this.handleNumberChange}/>
              // <Input placeholder='市场价格' className='clearValue'/>
            )}
          </Form.Item>

          <Form.Item label="销售价格" {...formItemLayout} help={number.errorMsg || tips2}>
            {getFieldDecorator('selling', {
              initialValue: isEdit ? editGoodData.selling : '',
              rules: [{required: true, message: '请填写销售价格...'}]
            })(
              <InputNumber min={0.01} value={number.value} onChange={this.handleNumberChange}/>
              // <Input placeholder='销售价格' className='clearValue'/>
            )}
          </Form.Item>
          {/*发货日期*/}

          <Form.Item label="货 期" {...formItemLayout}>
            {getFieldDecorator('theDateOfIssuance', {
              initialValue: isEdit ? editGoodData.thedateofissuance : '',
              rules: [{required: true, message: '请填写发货日期...'}]
            })(
              <Input placeholder='请填写发货日期' className='clearValue'/>
            )}
          </Form.Item>

          {/*规格状态*/}
          <Form.Item label="规格状态" {...formItemLayout}>
            {getFieldDecorator('specStatus', {
              initialValue: isEdit ? editGoodData.spec_status : []
            })(
              <Checkbox.Group>
                <Checkbox value="is_top">首页置顶</Checkbox>
                <Checkbox value="is_promotions">特惠活动</Checkbox>
                <Checkbox value="is_recommend">推荐</Checkbox>
              </Checkbox.Group>
            )}
          </Form.Item>


          <Form.Item label="展示描述" {...formItemLayout}>
            {getFieldDecorator('desc', {
              initialValue: isEdit ? editGoodData.desc : '',
              rules: [{
                // required: true,
                // message: '请填写描述...'
              }]
            })(
              <TextArea placeholder="Autosize height based on content lines" autosize={{minRows: 4}}/>
            )}
          </Form.Item>


          <Form.Item label="商品参数" {...formItemLayout}>
            {getFieldDecorator('parameter', {
              rules: [{
                // required: true,
                // message: '请填写参数...'
              }]
            })(
              // 富文本
              <BraftEditor isEdit={this.state.isEdit} tempParameter={editGoodData.parameter || null}/>
            )}
          </Form.Item>
          {/*该处理的问题的地方*/}

          <Form.Item>
            <div id='drawer-form-buttons'>
              <Button type="primary" className="drawer-form-button" onClick={window.close}>取消编辑</Button>
              <Button type="danger" className="rawer-form-button" onClick={this.handleOk}>保存配置</Button>
            </div>
          </Form.Item>

        </Form>

      </div>
    );
  }
}

const mapStateToProps = state => state.generatingGoods;
const WrappedNormalLoginForm = Form.create()(GeneratingGoods);   // ant上要求假的 如果不加这句代码就会失效
export default connect(mapStateToProps, action)(WrappedNormalLoginForm);
